using MaterialSkin.Controls;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace VideoAutoGenerator.UI.UserControls
{
    public partial class WorkPreviewControl : MaterialCard
    {
        private MaterialLabel titleLabel;
        private WebBrowser videoPlayer;
        private MaterialLabel videoInfoLabel;
        private MaterialButton playButton;
        private MaterialButton pauseButton;
        private MaterialButton stopButton;
        private string currentVideoPath;

        public WorkPreviewControl()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 创建控件
            CreateControls();

            // 设置布局
            SetupLayout();

            // 添加事件处理程序
            SetupEventHandlers();

            this.ResumeLayout(false);
        }

        private void CreateControls()
        {
            titleLabel = new MaterialLabel();
            videoPlayer = new WebBrowser();
            videoInfoLabel = new MaterialLabel();
            playButton = new MaterialButton();
            pauseButton = new MaterialButton();
            stopButton = new MaterialButton();
        }

        private void SetupLayout()
        {
            // 设置控件属性
            this.AutoScroll = true;
            this.Dock = DockStyle.Fill;
            this.Padding = new Padding(20);

            // 标题
            titleLabel.Text = "作品预览";
            titleLabel.AutoSize = true;
            titleLabel.Font = new Font(titleLabel.Font.FontFamily, 16, FontStyle.Bold);
            titleLabel.Location = new Point(10, 10);

            // 视频播放器
            videoPlayer.Width = 560;
            videoPlayer.Height = 315; // 16:9 比例
            videoPlayer.Location = new Point(10, 50);
            videoPlayer.ScriptErrorsSuppressed = true;
            videoPlayer.AllowWebBrowserDrop = false;
            videoPlayer.IsWebBrowserContextMenuEnabled = false;
            videoPlayer.WebBrowserShortcutsEnabled = false;

            // 控制按钮
            playButton.Text = "播放";
            playButton.Width = 80;
            playButton.Location = new Point(10, 380);

            pauseButton.Text = "暂停";
            pauseButton.Width = 80;
            pauseButton.Location = new Point(100, 380);

            stopButton.Text = "停止";
            stopButton.Width = 80;
            stopButton.Location = new Point(190, 380);

            // 视频信息标签
            videoInfoLabel.Text = "请选择一个视频文件进行预览";
            videoInfoLabel.AutoSize = true;
            videoInfoLabel.Location = new Point(10, 420);

            // 添加控件到面板
            this.Controls.Add(titleLabel);
            this.Controls.Add(videoPlayer);
            this.Controls.Add(playButton);
            this.Controls.Add(pauseButton);
            this.Controls.Add(stopButton);
            this.Controls.Add(videoInfoLabel);
        }

        private void SetupEventHandlers()
        {
            playButton.Click += PlayButton_Click;
            pauseButton.Click += PauseButton_Click;
            stopButton.Click += StopButton_Click;
        }

        private void PlayButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(currentVideoPath) && File.Exists(currentVideoPath))
            {
                try
                {
                    // 使用HTML5视频标签播放视频
                    string html = $@"
                        <html>
                        <head>
                            <style>
                                body {{ margin: 0; background: #000; }}
                                video {{ width: 100%; height: 100%; object-fit: contain; }}
                            </style>
                        </head>
                        <body>
                            <video id='videoPlayer' controls autoplay>
                                <source src='file:///{currentVideoPath.Replace("\\", "/")}' type='video/mp4'>
                                您的浏览器不支持视频播放。
                            </video>
                        </body>
                        </html>";

                    videoPlayer.DocumentText = html;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"播放视频时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选择有效的视频文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void PauseButton_Click(object sender, EventArgs e)
        {
            // 在WebBrowser中暂停视频较为复杂，这里仅作示意
            // 实际应用中可能需要使用Windows Media Player控件或其它专门的视频播放控件
            MessageBox.Show("暂停功能需要使用专业的视频播放控件实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            videoPlayer.Navigate("about:blank");
            videoInfoLabel.Text = "播放已停止";
        }

        public void LoadVideo(string videoPath)
        {
            if (File.Exists(videoPath))
            {
                currentVideoPath = videoPath;
                string fileName = Path.GetFileName(videoPath);
                string fileSize = GetFileSize(videoPath);
                string fileDate = File.GetCreationTime(videoPath).ToString("yyyy-MM-dd HH:mm:ss");

                // 尝试获取视频时长和分辨率信息
                string videoInfo = GetVideoInfo(videoPath);

                videoInfoLabel.Text = $"文件名: {fileName}\n文件大小: {fileSize}\n创建时间: {fileDate}\n{videoInfo}";

                // 自动播放视频
                PlayButton_Click(null, null);
            }
        }

        private string GetFileSize(string filePath)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(filePath);
                long size = fileInfo.Length;

                if (size < 1024)
                    return $"{size} B";
                else if (size < 1024 * 1024)
                    return $"{size / 1024.0:F2} KB";
                else if (size < 1024 * 1024 * 1024)
                    return $"{size / (1024.0 * 1024.0):F2} MB";
                else
                    return $"{size / (1024.0 * 1024.0 * 1024.0):F2} GB";
            }
            catch
            {
                return "未知";
            }
        }

        private string GetVideoInfo(string videoPath)
        {
            try
            {
                // 使用FFmpeg获取视频信息
                string ffmpegPath = Core.ConfigManager.Instance.GetString("ffmpeg.path", "ffmpeg");
                ProcessStartInfo processInfo = new ProcessStartInfo
                {
                    FileName = ffmpegPath,
                    Arguments = $"-i \"{videoPath}\"",
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using (Process process = Process.Start(processInfo))
                {
                    string output = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    // 解析视频信息
                    string duration = "未知";
                    string resolution = "未知";

                    // 提取时长信息
                    int durationIndex = output.IndexOf("Duration:");
                    if (durationIndex >= 0)
                    {
                        int commaIndex = output.IndexOf(",", durationIndex);
                        if (commaIndex > durationIndex)
                        {
                            duration = output.Substring(durationIndex + 10, commaIndex - durationIndex - 10).Trim();
                        }
                    }

                    // 提取分辨率信息
                    int resolutionIndex = output.IndexOf("Video:");
                    if (resolutionIndex >= 0)
                    {
                        // 简化处理，实际应用中可能需要更复杂的解析
                        int startIndex = output.IndexOf(",", resolutionIndex);
                        if (startIndex > 0)
                        {
                            int endIndex = output.IndexOf(",", startIndex + 1);
                            if (endIndex > startIndex)
                            {
                                resolution = output.Substring(startIndex + 1, endIndex - startIndex - 1).Trim();
                            }
                        }
                    }

                    return $"时长: {duration}\n分辨率: {resolution}";
                }
            }
            catch (FileNotFoundException ex)
            {
                // 处理文件未找到的异常
                MessageBox.Show($"FFmpeg未找到: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "时长: 未知\n分辨率: 未知";
            }
            catch (UnauthorizedAccessException ex)
            {
                // 处理无权限访问的异常
                MessageBox.Show($"无权限访问视频文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "时长: 未知\n分辨率: 未知";
            }
            catch (Exception ex)
            {
                // 处理其他未知异常
                MessageBox.Show($"获取视频信息时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "时长: 未知\n分辨率: 未知";
            }
        }
    }
}